package com.learn.config;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;

/**
 * @author DJJ_F
 * @version 1.0
 * @date 2025/02/11
 * @description mybatis配置类，需要编写SqlSessionFactoryBean和MapperScannerConfigurer
 */
public class MyBatisConfig {
    @Bean
    SqlSessionFactoryBean getSqlSessionFactory(DataSource dataSource, ApplicationContext applicationContext) throws IOException {
        SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
        // 设置xml的位置
        factory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));
        factory.setDataSource(dataSource);
        // 类型别名的包，是实体类的包
        factory.setTypeAliasesPackage("com.learn.pojo");
        return factory;
    }

    @Bean
    MapperScannerConfigurer getMapperScanner() {
        MapperScannerConfigurer mapperScanner = new MapperScannerConfigurer();
        // mapper扫描器，扫描mapper接口的包
        mapperScanner.setBasePackage("com.learn.mapper");
        return mapperScanner;
    }

}
